<template>
    <el-form-item :label="label" :prop="prop"
        :rules="!readonly ? (rules || [{ required: required, message: `${label}不能为空`, trigger: 'blur' }]) : null"
        :class="{ 'readonly-form-item': readonly }">

        <!-- 只读状态显示 -->
        <span v-if="readonly" class="readonly-content">
            {{ displayValue || '-' }}
        </span>

        <!-- 可编辑状态显示 -->
        <el-select v-else v-model="selectedPartnerId" :disabled="disabled" filterable remote clearable reserve-keyword
            :remote-method="remoteSearch" :loading="loading" :placeholder="placeholder || `请选择${label}`"
            @change="handleChange" style="width: 400px">

            <!-- Fixed first row for type filter -->
            <el-option class="partner-type-filter" disabled :value="''">
                <div @click.stop>
                    <el-radio-group v-model="partnerType" size="small" @change="handleTypeChange"
                        style="pointer-events: auto">
                        <el-radio-button label="all">全部</el-radio-button>
                        <el-radio-button label="customer">客户</el-radio-button>
                        <el-radio-button label="supplier">供应商</el-radio-button>
                    </el-radio-group>
                </div>
            </el-option>

            <!-- Regular partner options -->
            <el-option v-for="partner in options" :key="partner.id" :label="partner.name" :value="partner.id">
                <span style="float: left">{{ partner.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ partner.objType.name }}
                </span>
            </el-option>
        </el-select>
    </el-form-item>
</template>

<script>
import { ElMessage } from 'element-plus'
import { DataPage } from '../../network/communicationConverter'
import { Definition } from '../../engine/common/definition'
import { TargetObjectFilter, TargetObjectType, TargetObjectPlatformType } from '../../engine/targetOrg/targetObject'
import {Engine} from '../../engine/engine'

export default {
    name: 'PartnerSelect',
    props: {
        modelValue: {
            type: Object,
            default: null
        },
        label: {
            type: String,
            default: '往来单位'
        },
        prop: {
            type: String,
            default: 'partner'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        readonly: {
            type: Boolean,
            default: false
        },
        required: {
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: ''
        },
        rules: {
            type: Array,
            default: null
        },
        basicUiAction: {
            type: Object,
            required: true
        },
        initialPartnerType: {
            type: String,
            default: 'all' // 默认值
        },
        targetObjectPlatformTypeProps: {
            type: Number,      // TargetObjectPlatformType
            default: null // 默认值
        }
    },
    emits: ['update:modelValue', 'change'],
    data() {
        let ret = {
            selectedPartnerId: null,
            partnerType: this.initialPartnerType, // 使用props初始化
            lastPartnerType: this.initialPartnerType,
            options: [],
            filteredOptions: [],
            loading: false,
            lastQuery: '',
            filter: new TargetObjectFilter(),
            targetObjectPlatformType: this.targetObjectPlatformTypeProps,            
        }

        if(ret.targetObjectPlatformType == null && (!Engine.getOrgSettings().supportTemporarySupplier || !Engine.getOrgSettings().supportTemporaryCustomer) )
        {
            ret.targetObjectPlatformType = TargetObjectPlatformType.TUserCreated;
        }

        return ret;
    },
    computed: {
        displayValue() {
            return this.modelValue?.name || ''
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.selectedPartnerId = val.id

                    // 如果候选项没有当前值，则selectedPartnerId 使用名称，不然回显示id
                    if (val.name != null && !this.options.some(opt => opt.id === this.modelValue.id)) {
                        this.selectedPartnerId = val.name;
                    }
                }
            }
        },
    },
    methods: {
        handleTypeChange() {
            // console.log('handleTypeChange this readonly', this.readonly)
            if (this.partnerType == 'all') {
                this.filter.objType = null
            }
            else if (this.partnerType == 'customer') {
                this.filter.objType = TargetObjectType.TCustomer
            } else if (this.partnerType == 'supplier') {
                this.filter.objType = TargetObjectType.TSupplier
            }
            this.remoteSearch(this.lastQuery)
        },
        async remoteSearch(query) {
            if ((query + this.partnerType) == (this.lastQuery + this.lastPartnerType)) return
            if (!this.basicUiAction) return

            this.lastQuery = query
            this.lastPartnerType = this.partnerType
            this.filter.mixedLikeInfo = query
            this.loading = true

            try {
                const res = await this.basicUiAction.getTargetObjectData({
                    pageInfo: new DataPage(1, 0, Definition.gDefualPullDownPageSize),
                    filter: this.filter.toJson()
                })

                if (res.data && res.data.dataList.length > 0) {
                    this.updateOption(res.data.dataList);
                }
            } catch (error) {
                console.error('搜索往来单位失败:', error)
                ElMessage.error('搜索往来单位失败')
            } finally {
                this.loading = false
            }
        },
        handleChange(val) {
            // console.log('partner handleChange:', val)
            const selectedPartner = this.options.find(u => u.id === val)
            if (selectedPartner) {
                // console.log('partner selected:', selectedPartner)
                this.$emit('update:modelValue', selectedPartner)
                this.$emit('change', selectedPartner)
            }
        },
        async loadDefaultOptions() {
            // console.log('loadDefaultOptions partnerType:', this.partnerType)
            if (!this.basicUiAction) return

            if (this.partnerType == 'all') {
                this.filter.objType = null
            }
            else if (this.partnerType == 'customer') {
                this.filter.objType = TargetObjectType.TCustomer
            } else if (this.partnerType == 'supplier') {
                this.filter.objType = TargetObjectType.TSupplier
            }

            this.loading = true
            try {
                const res = await this.basicUiAction.getTargetObjectData({
                    pageInfo: new DataPage(1, 0, Definition.gDefualPageSize),
                    filter: this.filter.toJson()
                })

                if (res.data && res.data.dataList.length > 0) {
                    this.updateOption(res.data.dataList);
                }
            } catch (error) {
                console.error('加载往来单位失败:', error)
            } finally {
                this.loading = false
            }
        },

        updateOption(dataList) {
            this.options = dataList;

            // 判断是否有因为显示而进行的trick ，如有，并且有选中的值，则重新设置选中值
            if (this.selectedPartnerId == this.modelValue?.name  && this.modelValue?.id != null &&  this.options.some(opt => opt.id === this.modelValue.id)) {
                this.selectedPartnerId = this.modelValue.id;
                return;
            }
        },
    },


    mounted() {
        this.$nextTick(() => {
            // 重新从prop 赋值，避免加载延时初始值与赋值不一致问题
            this.partnerType = this.initialPartnerType;
            if (this.targetObjectPlatformType != null) {
                this.filter.objPlatformType = this.targetObjectPlatformType;
            }
            this.loadDefaultOptions();
        })
    }
}
</script>

<style scoped>
/* 只读状态下的表单项目样式 */
.readonly-form-item :deep(.el-form-item__label) {
    font-size: 13px;
    color: #909399;
}

.readonly-content {
    display: flex;
    align-items: center;
    width: 400px;
    padding: 0 10px;
    height: 40px;
    font-size: 15px;
    color: #303133;
    vertical-align: middle;
    margin-top: -5px;
}

/* 取消只读状态下的必填标记 */
.readonly-form-item :deep(.el-form-item__label::before) {
    content: none !important;
}

.partner-type-filter {
    height: auto !important;
    padding: 8px 20px;
    border-bottom: 1px solid #ebeef5;
    cursor: default !important;
}

.partner-type-filter :deep(.el-radio-group) {
    width: 100%;
    display: flex;
    justify-content: space-between;
    pointer-events: auto !important;
}

.partner-type-filter :deep(.el-radio-button) {
    flex: 1;
    pointer-events: auto !important;
}

.partner-type-filter :deep(.el-radio-button__inner) {
    width: 100%;
    pointer-events: auto !important;
}
</style>